package servlets;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import dataTypes.*;


@SuppressWarnings("serial")
public class validationServlet extends HttpServlet {

	public validationServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		int bId = Integer.parseInt(request.getParameter("bId"));

		deal dl = null;
		List<deal> results=appManager.getInstance().getActiveDealsByBusiness(bId);
		
		if (!results.isEmpty()){
			
			doResponse(response, results, bId, 2,0);
		}
		else
			response.sendRedirect("/adminmanage.html?bId="+bId+"&result=1");			

	}


	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		int bId = Integer.parseInt(request.getParameter("bId"));
		long num = Long.parseLong(request.getParameter("num"));

		boolean b=appManager.getInstance().isBusiness(bId);
		if (!b){
			response.sendRedirect("/adminlogin.html");
			return;
		}

		deal d= appManager.getInstance().validateCoupon(bId,num);
		List<deal> results=appManager.getInstance().getActiveDealsByBusiness(bId);
		if (d==null&&results.isEmpty()){
			response.sendRedirect("/adminmanage.html?bId="+bId+"&result=1");}
		else if(!results.isEmpty()&&d==null)
			{//coupon - when taken should be updated on local list as well
				
				doResponse(response, results, bId, 0,0);	
				return;
			}
			
		

		int numOfCoupons = d.getNumOfCoupons();
		int numPurchased = d.getNumPurchased();

		doResponse(response, results, bId, 1,d.getKey().getId());

		//response.sendRedirect("/adminmanage.html?bId="+bId+"&result=1");
	}

	private void doResponse(HttpServletResponse response, List<deal> deals, int bId, int flag,long dId) throws IOException{

		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/html; charset=UTF-8");
		response.setHeader("Content-Encoding","UTF-8");

		response.getWriter().println("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
		response.getWriter().println("<html>");
		response.getWriter().println("<head>");
		response.getWriter().println("<title>CoupoNow</title>");
		response.getWriter().println("<style type='text/css'> body {background-image:url('light_blue.jpg');}</style>");
		response.getWriter().println("<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>");
		response.getWriter().println("<link type='text/css' rel='stylesheet' href='couponow.css'>");
		response.getWriter().println("<script src='SpryAssets/SpryValidationTextField.js' type='text/javascript'></script>");
		response.getWriter().println("<link type='text/css' rel='stylesheet' href='SpryAssets/SpryValidationTextField.css'>");
		response.getWriter().println("<SCRIPT TYPE='text/javascript'>");
		//response.getWriter().println("function getbId(){var bId = location.href.substring((location.href.indexOf('bId=')+4), location.href.indexOf('&result')); return bId;}");
		//response.getWriter().println("function getResult(){var result = location.href.substring((location.href.indexOf('result=')+7), location.href.length); return result;}");
		response.getWriter().println("</script>");
		response.getWriter().println("</head>");

		response.getWriter().println("<body>");
		response.getWriter().println("<div id='general'> <div id='heading1'> <div id='image'><a href='/'><img src='heading1.png' width='474' height='166'" +
		" alt='Logo' style='border-style:none'/></a></div><div id='yoursource'><img src='pic1.png' height='126' width='540'/></div></div>");

		response.getWriter().println("<br class='clearfloat' />");

		response.getWriter().println("<div id='body'>");

		response.getWriter().println("<div style='height:auto; text-align:center'>"+
				"<p> <table width='1000' border='0' style='background:#ececec&gt;"+
				"  &lt;tr&gt;"+
				"&lt;td width= background-color: #333; background-color: #333; color: #FFF; font-family: Verdana, Geneva, sans-serif; font-size: 20px; font-style: normal; font-weight: bolder;'45'><div align='center'></div></td>"+
				"<td width='49'><div align='center'></div></td>" + 
				"<td width='49'><div align='center'></div></td>" + 
				"<td width='49'><div align='center'></div></td>" + 
				"<td width='49'><div align='center'></div></td>" + 
				"<td width='49'><div align='center'></div></td>" + 
				"<td width='49'><div align='center'></div></td>" + 
				"<td width='116'><div align='center'>צור קשר</div></td>"+
				"<td width='68'><div align='center'>אודות</div></td>"+
		"<td width='136'><div align='center'>הצעת פעילות</div></td></tr></table></div>");


		for (deal d:deals){
			if ((dId!=0)&&d.getKey().getId()==dId){
				double percent = d.getPercent()*100 / d.getAmount();
				response.getWriter().println("<div class='dls' style='margin-top:24px;'><strong>  אחוז הנחה: </strong>" + percent + 
				" <strong>  שעת סיום: </strong>" + d.getEnd().getHours()+ ":" + d.getEnd().getMinutes() +" <strong>  סך הכל קופונים: </strong>" + d.getNumOfCoupons() + " <strong style="+"color:red"+">  נרכשו עד כה: </strong>" + d.getNumPurchased() + " <strong>  מומשו עד כה: </strong>" + d.getNumUsed() +
				" <img src='" + d.getBusiness().getPhotoLink() +  "'class='img2' style='margin-left:12px;'/></div>");
				
			}
			else{
				double percent = d.getPercent()*100 / d.getAmount();
				response.getWriter().println("<div class='dls' style='margin-top:24px;'><strong>  אחוז הנחה: </strong>" + percent + 
				" <strong>  שעת סיום: </strong>" + d.getEnd().getHours()+ ":" + d.getEnd().getMinutes() +" <strong>  סך הכל קופונים: </strong>" + d.getNumOfCoupons() + " <strong>  נרכשו עד כה: </strong>" + d.getNumPurchased() + " <strong>  מומשו עד כה: </strong>" + d.getNumUsed() +
				" <img src='" + d.getBusiness().getPhotoLink() +  "'class='img2' style='margin-left:12px;'/></div>");
			}
		}
		response.getWriter().println("<div id='bottons'>"+
				"<FORM ACTION='/validationservlet' method='post'>"+
				"<INPUT TYPE='hidden' id='busid' NAME='bId' VALUE='"+ bId +"'><P>"+
				"<input type='submit' VALUE='בדוק קופון' />"+
				"<span id='sprytextfield'><span class='textfieldRequiredMsg'>.שדה חובה”</span>"+
				"<span class='textfieldInvalidFormatMsg'>אנא הכנס מספר</span>"+
				"<input type='text' name ='num' size='30' value=''/> </span>"+
		"</FORM></div>");

		response.getWriter().println("<div style='height:auto; text-align:center'>"+
				"<table width='1000' border='0'style='background:#ececec&gt;"+
				"&lt;tr&gt;"+
				"&lt;td width= background-color: #333; background-color: #333; color: #FFF; font-family: Verdana, Geneva, sans-serif; font-size: 14px;'45'><div align='center'></div><td width='0' height='2'></td>"+
				"<td width='48' height='39'><div align='center'></div></td>"+
				"<td width='48'><div align='center'></div></td>"+
				"<td width='48'><div align='center'></div></td>"+
				"<td width='389'><div align='center'></div></td>"+
				"<td width='69'><div align='center'>תקנון</div></td>"+
				"<td width='116'><div align='center'>שאלות נפוצות</div></td>"+
				"<td width='73'><div align='center'>צור קשר</div></td>"+
				"<td width='64'><div align='center'>אודות</div></td>"+
				"<td width='103'><div align='center'>הצעות פעילות</div></td>"+
		"</tr></table></p></div></div></div>");

		response.getWriter().println("<script type='text/javascript'>var sprytextfield = new Spry.Widget.ValidationTextField('sprytextfield', 'integer');</script>");

		if (flag == 1)
			response.getWriter().println("<SCRIPT TYPE='text/javascript'>alert('!קופון התקבל')</script></body></html>");
		if (flag == 0)
			response.getWriter().println("<SCRIPT TYPE='text/javascript'>alert('!קוד לא תקין/קופון כבר נלקח')</script></body></html>");
		

	}


}